//引入创建store对象的configureStore
// 引入创建slice对象的createSlice(slice集成了action和reducer)
import { configureStore, createSlice, createAsyncThunk } from '@reduxjs/toolkit'

// 初始化数据
const initialtestState = {
  count: 0,
  msg: 'hello',
}

// 新增代码:
//定义执行异步的函数.要求返回值是一个promise
// 这里的yyy,会体现在action对象的type上面
export const asyncMsg = createAsyncThunk('yyy', () => {
  return new Promise<string>((resolve, reject) => {
    setTimeout(() => {
      resolve('hahaha')
      // reject('123')
    }, 1000)
  })
})

// 创建slice
export const testSlice = createSlice({
  name: 'xxx', //slice的名称
  initialState: initialtestState, // 初始化数据
  // 创建reducer
  reducers: {
    // 创建同步action
    add: function (state, action) {
      // @reduxjs/toolkit支持直接修改state数据
      state.count = state.count + 1
    },
    sub: (state, action) => {
      // 在@reduxjs/toolkit中action中传入的数据,属性名统一写成payload
      state.count = state.count - action.payload
    },
  },
  // 新增代码:
  // 为异步操作定义action
  extraReducers(builder) {
    builder.addCase(asyncMsg.pending, () => {
      console.log('正在异步操作')
    })
    builder.addCase(asyncMsg.fulfilled, (state, action) => {
      console.log('成功', state, action)
      state.msg = action.payload
    })
    builder.addCase(asyncMsg.rejected, (state, action) => {
      console.log('失败')
    })
  },
})
// 创建store对象
const store = configureStore({
  // 这里相当于合并reducer
  reducer: {
    test: testSlice.reducer,
  },
})
// 导出store对象
export default store
// 导出action
export const { add, sub } = testSlice.actions

// ReturnType 是ts中内置类型,无需引入
// typeof store.getState 是在ts编译的时候执行,返回的是redux中所有数据的ts数据类型
export type RootState = ReturnType<typeof store.getState> //解决获取状态时,ts编译错误
export type AppDispatch = typeof store.dispatch // 解决异步操作时dispatch位置的ts编译错误
